# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from solar import SolarReader
from datetime import datetime
from money import Money
import MySQLdb
from dbquery import executeQuery
import feedparser
import settings
import random
import chart as charts
import os
import chartserver as chartserver

def readChart(png):
  png.seek(0)
  r = HttpResponse(png.read(), 'image/png')
  png.close()
  return r

def index(request):
    hours = request.GET.get('hours', '72')
    reader = SolarReader()
    maxData = executeQuery("""select max(watts),0 from solar_data where time > DATE(NOW())
                              union
                              select max(watts),1 from solar_data""")
    maxWatts = maxData[0][0]
    maxLifetime = maxData[1][0]
    now = datetime.now()
    history = reader.getHistory(1)
    energy = (history[0][1],history[0][2],history[0][3])    
    money = Money()
    money = money.computeMoney()

    bestDay = reduce(lambda x,y: (x[2] + x[3]) > (y[2] + y[3]) and x or y,money)
    worstDay = reduce(lambda x,y: (x[2] + x[3]) < (y[2] + y[3]) and x or y, money)
    
   
    total = reduce(lambda x,y: x+y,(map(lambda x: x[1], money)),0)


    payback = (20000 / (total / len(money))) - len(money)
    paybackYears = payback / 365.0
    rateOfReturn = (((365.0 / len(money)) * total) / 20000)
    hours = int(request.GET.get('hours', '72'))
    
    readout = (("Watts", energy[0]),
               ("kWh Today", energy[1]),
               ("kWh Lifetime", energy[2]),
               ("Carbon Dioxide Saved", "%.2f pounds" % (float(energy[2])*0.81)),  #810 lbs co2 per 1000 kwh, according to terrpass
               ("Max Watts Today", maxWatts),
               ("Max Watts Lifetime", maxLifetime),
               ("Money made Today", "$%.4f" % money[0][1]),
               ("Days on record", len(money)),
               ("Total Money", "$%.4f" % total),
               ("Payback in", "%d days" % payback),
               ("Payback in", "%.2f years" % paybackYears),
               ("Annual Rate of Return", "%.4f%%" % (rateOfReturn * 100)),
               ("Best Day Ever", "%.2f kWh on %s" % ((bestDay[2] + bestDay[3]), bestDay[0].strftime("%m-%d-%Y"))),
               ("Worst Day Ever", "%.2f kWh on %s" % ((worstDay[2] + worstDay[3]), worstDay[0].strftime("%m-%d-%Y"))),
               )

    feed = feedparser.parse("http://rss.wunderground.com/auto/rss_full/CA/Oakland.xml?units=both")
    current = feed.entries[0].title
    main_chart = chartserver.drawChart(hours)
    total_chart = chartserver.drawBarChart("total")
    daily_chart = chartserver.drawBarChart("daily")
    return render_to_response('index.html', { 
                        'bestDay' : bestDay,
                        'worstDay' : worstDay, 
                        'hours' : hours,
                        'readout' : readout,
                        'money' : money[:7],
                        'current' : current,
                        'main_chart_url' : main_chart.get_url(),
                        'total_chart_url' : total_chart.get_url(),
                        'daily_chart_url' : daily_chart.get_url()
                         })

def chart(request):
  hours = int(request.GET.get('hours', '72'))
  name = charts.drawChart(hours)
  r = readChart(name)
  return r

def daily(request):
  type = request.GET.get('type', 'total')
  name = charts.drawBarChart(type) 
  r = readChart(name)
  return r
    
    

  
if __name__ == "__main__":
  print fileName("chart")
 
